import {storeBindingsBehavior} from "mobx-miniprogram-bindings";
import base from "@src/store/base";
import member from "@src/store/member";
import {getCategoryAvailable, getMemberGiveConfig, memberGiveAway} from "@src/api/member";
import router from "@src/router";
import $math from "@src/common/math";
import color from "@src/common/color";
import $cache from "@src/common/wxCache";
import memberPayBehavior from "@src/common/memberPayBehavior";

Component({
  behaviors: [storeBindingsBehavior, memberPayBehavior],
  storeBindings: [{
    store: base,
    fields: ['themeColor', 'themeTitleColor'],
  }, {
    store: member,
    fields: ['isMember', 'memberName', 'categoryName', 'categoryImage', 'wxName'],
    actions: ['getBaseInfo'],
  }],
  data: {
    blessings: [],
    cardList: [],
    currentCategory: null,
    toWhichCard: null,
    themeColorRgba: null,
    money: null,
  },
  observers: {
    'themeColor': function (themeColor) {
      this.setData({themeColorRgba: color.HexToRGB(themeColor, 20)})
    },
    'currentCategory': function (category) {
      // 计算需要支付的金额
      let money = 0;
      if (category.payType === 2) {
        money = $math.div(category.payCost, 100, 2);
      } else if (category.payType === 3) {
        money = $math.div(category.rechargeCost, 100, 2);
      } else {
        money = $math.div(category.payCost, 100, 2);
      }
      this.setData({money: money})
    }
  },
  methods: {
    onLogin() {
      this.fetchData();
    },
    fetchData() {
      getMemberGiveConfig().then(res => {
        if (res.code === 0) {
          let giveConfig = res.data;
          if (!giveConfig.enableGive) {
            wx.showModal({
              title: "提示", content: "商家未开启赠送配置", success: () => {
                router.push({name: "index"});
              }
            });
            return;
          }
          if (giveConfig.blessings) {
            let blessings = JSON.parse(giveConfig.blessings);
            let msgIndex = 0;
            let changeSendMessage = blessings[msgIndex].desc;
            this.setData({blessings, changeSendMessage, msgIndex})
          } else {
            this.setData({blessings: []})
          }
        }
      })
      getCategoryAvailable().then(res => {
        let cardList = res.data;
        if (!cardList || cardList.length === 0) {
          wx.showModal({
            title: "提示", content: "商家未配置会员卡", success: () => {
              router.push({name: "index"});
            }
          });
          return;
        }
        let currentCategory = cardList[0].category
        this.setData({cardList: cardList, currentCategory: currentCategory})
      })
    },

    handleSwipeCardClick(e) {
      let item = e.currentTarget.dataset.item;
      let currentCategory = item.category;
      let toWhichCard = "card-" + item.category.id; //跳转卡
      this.setData({currentCategory, toWhichCard})
    },

    handleMsgInput(e) {
      this.setData({changeSendMessage: e.detail.value})
    },

    handleChangeMsg(e) {
      let item = e.currentTarget.dataset.item;
      let index = e.currentTarget.dataset.index;
      this.setData({changeSendMessage: item.desc, msgIndex: index})
    },

    handleBuy() {
      wx.showLoading({title: "购买中...", mask: true});
      let data = {
        blessing: this.data.changeSendMessage,
        categoryId: this.data.currentCategory.id,
        extraBalance: 0,
        mercNo:$cache.get('themeConfig-mall').mercNo
      };
      memberGiveAway(data).then(res => {
        wx.hideLoading();
        let {orderCode, receiveCode} = res.data;
        if (res.data.needPay) {
          let payData = {
            orderNo: orderCode,
            payFee: this.data.money * 100,
            payChannels: ["wx"],
            hasDiscount: false
          }
          this.toMemberPay(payData).then(res => {
            wx.nextTick(() => {
              this.toDetailPage(receiveCode);
            })
          })
        } else {
          wx.nextTick(() => {
            this.toDetailPage(receiveCode);
          })
        }
      })
    },
    toDetailPage(receiveCode) {
      wx.showModal({
        title: "提示",
        content: "购买成功",
        cancelText: "继续购买",
        confirmText: "去赠送",
        success: (res) => {
          if (res.confirm) {
            router.push({name: "member/sendGiftDetail", params: {receiveCode: receiveCode}})
          }
        }
      });
    },
  }
})
